<?php

class webmail extends Controller {

	public function index() {
		header('Location: '.WEB_ROOT.'webmail/menu');
	}
	
	public function view($mailbox = INBOX, $uid = 0) {
		if(!User::isLogged()) {
			header('Location: '.WEB_ROOT.'member/index');
			exit();
		}
		$mailbox = Imap::chooseMailbox($mailbox);
		if(empty($uid) || !is_numeric($uid)) $uid = 0;
		$this->vars['email'] = Email::findEmailByUid($mailbox,$uid);
		$this->vars['mailbox'] = $mailbox;
		switch($mailbox){
			case INBOX: $boxpath = "inbox"; break;
			case DRAFTS: $boxpath = "drafts"; break;
			case SENT: $boxpath = "sent"; break;
			case TRASH: $boxpath = "trash"; break;
			default: $boxpath = "folder/" . $mailbox; break;
		}
		$this->vars['mailboxes'] = Imap::getCustomMailboxes();
		$this->vars['boxpath'] = $boxpath;
		$this->vars['uid'] = $uid;
		$this->render('view');
	}
	
	public function search ($mailbox, $query) {
		if(!User::isLogged()){
			header('Location: '.WEB_ROOT.'member/index');
			exit();
		}
		
		$resok = true;
		if ( empty ( $mailbox ) ) {
			$mailbox = $_REQUEST['mailbox'];
		}
		$mailbox = Imap::chooseMailbox($mailbox);
		
		if ( empty ( $query ) )
		{
			if ( empty ( $_REQUEST['search'] ) )
				$resok = false;
			else
				$query = $_REQUEST['search'];
		}
		$this->vars['query'] = $query;
		$this->vars['search'] = 1;
		$query = "TEXT " . $query;
		$this->vars['title'] = 'Recherche';
		$this->vars['mailbox'] = $mailbox;
		if ( $resok )
			$this->vars['emails'] = Email::search($mailbox,$query);
		else
			$this->vars['emails'] = array ();
		$this->render('list');
	}
	
	public function menu() {
		if(!User::isLogged()) {
			header('Location: '.WEB_ROOT.'member/index');
			exit();
		}
		
		$this->vars['statusesbymb'] = array();
		$this->vars['count'] = 0;
		foreach($_SESSION['user']['mailboxes'] as $mailbox) {
			if($mailbox->fullname != SENT && $mailbox->fullname != DRAFTS) {
				$this->vars['statusesbymb'][$mailbox->fullname] = Imap::mailbox_status($mailbox->fullname);
				$this->vars['count'] += $this->vars['statusesbymb'][$mailbox->fullname]->unseen;
			}
		}
		$this->vars['mailboxes'] = Imap::getCustomMailboxes();
		$this->render('menu');
	}
	
	public function inbox($page = 1) {
		if(!User::isLogged()) {
			header('Location: '.WEB_ROOT.'member/index');
			exit();
		}
		$this->vars['title'] = 'R&eacute;ception';
		$this->vars['mailbox'] = INBOX;
		$this->vars['emails'] = Email::findInRange($page,INBOX);
		$this->render('list');
	}
	
	public function unread() {
		if(!User::isLogged()) {
			header('Location: '.WEB_ROOT.'member/index');
			exit();
		}
		
		$this->vars['count'] = 0;
		foreach($_SESSION['user']['mailboxes'] as $mailbox) {
			if($mailbox->fullname != SENT && $mailbox->fullname != DRAFTS) {
				$this->vars['statusesbymb'][$mailbox->fullname] = Imap::mailbox_status($mailbox->fullname);
				$this->vars['count'] += $this->vars['statusesbymb'][$mailbox->fullname]->unseen;
			}
		}
		
		$this->vars['emailsbymb'] = array();
		foreach($_SESSION['user']['mailboxes'] as $mailbox) {
			if($mailbox->fullname != SENT && $mailbox->fullname != DRAFTS) {
				$this->vars['emailsbymb'][] = array('mailbox' => $mailbox,'emails' => Email::findUnseen($mailbox->fullname));
			}
		}
		$this->render('unread');
	}
	
	public function drafts($page = 1) {
		if(!User::isLogged()) {
			header('Location: '.WEB_ROOT.'member/index');
			exit();
		}
		$this->vars['title'] = 'Brouillons';
		$this->vars['mailbox'] = DRAFTS;
		$this->vars['emails'] = Email::findInRange($page,DRAFTS);
		$this->render('list');
	}
	
	public function sent($page = 1) {
		if(!User::isLogged()) {
			header('Location: '.WEB_ROOT.'member/index');
			exit();
		}
		$this->vars['title'] = 'Envoy&eacute;s';
		$this->vars['mailbox'] = SENT;
		$this->vars['emails'] = Email::findInRange($page,SENT);
		$this->render('list');
	}
	
	public function trash($page = 1) {
		if(!User::isLogged()) {
			header('Location: '.WEB_ROOT.'member/index');
			exit();
		}
		$this->vars['title'] = 'Corbeille';
		$this->vars['mailbox'] = TRASH;
		$this->vars['emails'] = Email::findInRange($page,TRASH);
		$this->render('list');
	}
	
	public function folder($mailbox = INBOX, $page = 1) {
		if(!User::isLogged()) {
			header('Location: '.WEB_ROOT.'member/index');
			exit();
		}
		$this->vars['title'] = (strlen($mailbox) > 15) ? substr($mailbox,0,15).'...' : substr($mailbox,0,strlen($mailbox));
		$this->vars['mailbox'] = Imap::chooseMailbox($mailbox);
		$this->vars['emails'] = Email::findInRange($page,$this->vars['mailbox']);
		$this->render('list');
	}
	
	public function dossiers($mailbox = INBOX, $uid = 0) {
		if(!User::isLogged()) {
			header('Location: '.WEB_ROOT.'member/index');
			exit();
		}
		$mailbox = Imap::chooseMailbox($mailbox);
		if(empty($uid) || !is_numeric($uid)) $uid = 0;
		$this->vars['mailbox'] = $mailbox;
		$this->vars['uid'] = $uid;
		$this->vars['mailboxes'] = Imap::getCustomMailboxes();
		$this->render('dossiers');
	}
	
	/**
	 * Action next() chargeant les mails suivants dans la liste
	 * Appelée uniquement via ajax depuis une liste
	 */
	public function next() {
		if(User::isLogged()) {
			if(isset($_POST['mailbox']) && isset($_POST['page'])){
				extract($_POST);
				$this->setLayout(null);
				$this->vars['mailbox'] = $mailbox;
				$this->vars['emails'] = Email::findInRange($page,Imap::chooseMailbox($mailbox));
				$this->vars['mailboxes'] = Imap::getCustomMailboxes();
				$this->render('_listmails');
			}
		}
	}
	
	/**
	 * Action reload() rechargeant la première page de mails de la mailbox
	 * Appelée uniquement via ajax depuis une liste
	 */
	public function reload() {
		if(User::isLogged()) {
			if(isset($_POST['mailbox']) && isset($_POST['page'])){
				extract($_POST);
				$this->setLayout(null);
				$this->vars['mailbox'] = $mailbox;
				$this->vars['emails'] = Email::findInRangeFromTo(1,$page,Imap::chooseMailbox($mailbox));
				$this->render('_listmails');
			}
		}
	}
	
	public function attachment($mailbox = INBOX, $uid = 0, $mode = "download", $fileno = '') {
		ini_set('display_errors', 0);
		// Récupération de l'email
		$email = Email::findEmailByUid($mailbox,$uid);
		if(is_numeric($fileno)) {
			// Test du mode demandé
			if($mode == "download") {
				// Mise en place des headers
				header("Content-type: application/force-download");
				header("Content-Disposition: attachment; filename=\"".Email::header_charset_decode($email->attachments[$fileno]['filename'])."\"");
				header("Content-Length: ".filesize($email->attachments[$fileno]['data']));
				// Affichage du contenu de la pièce jointe
				echo html_entity_decode($email->attachments[$fileno]['data']);
			} else {
				// Mise en place des headers
				header("Content-type: application/octet-stream");
				header("Content-Disposition: attachment; filename=\"".Email::header_charset_decode($email->attachments[$fileno]['filename'])."\"");
				// Affichage du contenu de la pièce jointe
				echo html_entity_decode($email->attachments[$fileno]['data']);
			}
		}
	}
	
	public function movetofolder($currentmb = INBOX, $mailbox = INBOX, $uid = 0) {
		if(User::isLogged()) {
			$mbox = Imap::open($currentmb);
			if($currentmb != $mailbox){
				imap_mail_move($mbox, imap_msgno($mbox,$uid), $mailbox);
				imap_delete($mbox, imap_msgno($mbox,$uid));
				imap_expunge($mbox);
			}
			Imap::close($mbox);
			switch($currentmb){
				case INBOX: $boxpath = "inbox"; break;
				case DRAFTS: $boxpath = "drafts"; break;
				case SENT: $boxpath = "sent"; break;
				case TRASH: $boxpath = "trash"; break;
				default: $boxpath = "folder/" . $mailbox; break;
			}
			header('Location: '.WEB_ROOT.'webmail/'.$boxpath);
		}
	}
	
	/**
	 * Action movetotrash()
	 * Appelée uniquement via ajax
	 */
	public function movetotrash() {
		if(User::isLogged()) {
			if(isset($_POST['mailbox']) && isset($_POST['uid'])){
				extract($_POST);
				$mbox = Imap::open($mailbox);
				if($mailbox != TRASH && $mailbox != DRAFTS && $mailbox != SENT){
					imap_mail_move($mbox, imap_msgno($mbox,$uid), TRASH);
				}
				imap_delete($mbox, imap_msgno($mbox,$uid));
				imap_expunge($mbox);
				Imap::close($mbox);
			}
		}
	}
	
	/**
	 * Action tagunread() permettant de tagger un mail comme étant non-lu
	 * Appelée uniquement via ajax
	 */
	public function tagunread() {
		if(User::isLogged()) {
			if(isset($_POST['mailbox']) && isset($_POST['uid'])){
				extract($_POST);
				$mailbox = Imap::open($mailbox);
				imap_clearflag_full($mailbox, imap_msgno($mailbox,$uid), "\\Seen");
				Imap::close($mailbox);
			}
		}
	}
	
	/**
	 * Action tagread() permettant de tagger un mail comme étant lu
	 * Appelée uniquement via ajax
	 */
	public function tagread() {
		if(User::isLogged()) {
			if(isset($_POST['mailbox']) && isset($_POST['uid'])){
				extract($_POST);
				$mailbox = Imap::open($mailbox);
				imap_setflag_full($mailbox, imap_msgno($mailbox,$uid), "\\Seen");
			}
		}
	}
}